<template>
  <div class="community-list"
    @scroll.passive="handleScroll"
    ref="scrollContainer"
  >
    <div
      v-for="(post, index) in postVos"
      :key="index"
      class="post-item"
      @click="openPostDetail(post)"
    >
      <!-- 卡片容器 -->
      <div class="post-card">
        <!-- 图片区域 -->
        <div class="image-container">
          <img
            :src="post.imageUrls[0]"
            alt="post image"
            class="post-image"
          >
        </div>

        <!-- 内容区域 -->
        <div class="content-container">
          <h3 class="post-title">{{ post.title }}</h3>

          <div class="meta-info">
            <!-- 左侧用户信息 -->
            <div class="user-info">
              <img
                :src="post.authorImg"
                alt="avatar"
                class="avatar"
                @click="router.push('/user/' + post.authorId)"
              >
              <span class="username">{{ post.authorName }}</span>
            </div>

            <!-- 右侧互动信息 -->
            <div class="interaction-info">
              <div class="interaction-item" @click.stop="handleLike(post)">
                <img
                  :src="post.isLike ? likedIcon : likeIcon"
                  alt="like"
                  class="icon"
                >
                <span>{{ post.likeCount }}</span>
              </div>
              <div class="interaction-item" @click.stop="handleFavorite(post)">
                <img
                  :src="post.isFavorite ? favoritedIcon : favoriteIcon"
                  alt="favorite"
                  class="icon"
                >
                <span>{{ post.favoriteCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <PostDetail
    v-if="showDetail"
    :postdata="selectedPost"
    @close="showDetail = false"
    @deleted="handlePostDeleted"

  />
</template>

<script setup>
import { onMounted,ref,defineProps } from 'vue'
import { likePost,favoritePost } from '@/api/CommunityApi.js'
import PostDetail from '@/views/home/community/CommunityPostDetails.vue' // 假设你写在单独组件里


import likeIcon from '@/assets/community/like.png'
import likedIcon from '@/assets/community/liked.png'
import favoriteIcon from '@/assets/community/favorite.png'
import favoritedIcon from '@/assets/community/favorited.png'
import router from '@/router'

const showDetail = ref(false)
const selectedPost = ref(null)

const emit = defineEmits(['refresh','load-more']) // 通知上层的 community

const scrollContainer = ref(null)

const handlePostDeleted = () => {
  emit('refresh')  // 继续往上传递事件
  showDetail.value = false
}

const handleScroll = () => {
  const el = scrollContainer.value
  if (!el) return

  const bottomReached = el.scrollTop + el.clientHeight >= el.scrollHeight - 20
  if (bottomReached) {
    emit('load-more') // 通知父组件加载下一页
  }
}

const openPostDetail = (post) => {
  selectedPost.value = post
  showDetail.value = true
}

const handleLike = async (post) =>{

  // 避免重复点击
  if (post.isUpdatingLike) return;
  // 添加状态锁标志
  post.isUpdatingLike = true;

  try {
    post.isLike = !post.isLike;
    if(post.isLike){
      post.likeCount++;
    }
    else {
      post.likeCount = post.likeCount - 1 > 0 ? post.likeCount - 1 : 0;
    }
    const res = await likePost(post.id)
  } catch (error) {
    console.error('数据获取失败:', error)
  } finally {
    // 请求结束，释放锁
    post.isUpdatingLike = false;
  }
}

const handleFavorite = async (post) =>{

  // // 避免重复点击
  // if (post.isUpdatingFavorite) return;
  // // 添加状态锁标志
  // post.isUpdatingFavorite = true;

  try {
    post.isFavorite = !post.isFavorite;
    if(post.isFavorite){
      post.favoriteCount++;
    }
    else {
      post.favoriteCount = post.favoriteCount - 1 > 0 ? post.favoriteCount - 1 : 0;
    }
    const res = await favoritePost(post.id)
  } catch (error) {
    console.error('数据获取失败:', error)
  }
  // finally {
  //   post.isUpdatingFavorite = false;
  // }
}

const props = defineProps({
  postVos: {
    type: Array,
    required: true,
    default: () => []
  }
})
</script>

<style scoped>
.community-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  column-gap: 89px;
  row-gap: 40px;
  padding: 20px;

  width: 1311px;
  max-height: 600px;
  overflow: auto;
  margin: 0 auto;

  /* 隐藏滚动条 - 各浏览器兼容方案 */
  scrollbar-width: none;          /* Firefox */
  -ms-overflow-style: none;       /* IE & Edge */
}

.post-card {
  height: 272px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  max-width:100%;
  background-image: url('@/assets/community/PostBG.png'); /* 设置背景图 */
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain; /* 保持图片比例展示完整 */
  background-color: transparent;
}

.image-container {
  width: 198px;
  height: 120px;
  margin: 55px auto 10px auto;
  overflow: hidden;
  border-radius: 4px;
}

.post-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.content-container {
  padding: 0 10px;
}

.post-title {
  font-size: 19px;
  margin: 10px 0px 0px 20px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-family: SimSun;
  color:#746046;
}

.meta-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: 20px;
}

.avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #7f6748;
}

.username {
  font-size: 14px;
  color: #666;
}

.interaction-info {
  display: flex;
  gap: 12px;
  margin-right: 20px;
}

.interaction-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.icon {
  width: 18px;
  height: 18px;
  cursor: pointer;
}
</style>
